package service

import (
	"context"
	"gin_mall_tmp/dao"
	"gin_mall_tmp/model"
	"gin_mall_tmp/pkg/e"
	"gin_mall_tmp/pkg/utils"
	"gin_mall_tmp/serializer"
	"strconv"
)

type FavouriteService struct {
	ProductId   uint `json:"productId" form:"productId"`
	BossId      uint `json:"bossId" form:"bossId"`
	FavouriteId uint `json:"favouriteId" form:"favouriteId"`
	model.BasePage
}

func (service *FavouriteService) List(ctx context.Context, uId uint) serializer.Response {
	favouriteDao := dao.NewFavouriteDao(ctx)
	code := e.Success
	favourite, err := favouriteDao.ListFavourite(uId)
	if err != nil {
		utils.LogrusObj.Infoln("err", err)
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
			Error:  err.Error(),
		}
	}
	return serializer.BuildListResponse(serializer.BuildFavourites(ctx, favourite), uint(len(favourite)))
}

func (service *FavouriteService) Create(ctx context.Context, uId uint) serializer.Response {
	code := e.Success
	favouriteDao := dao.NewFavouriteDao(ctx)
	exist, _ := favouriteDao.FavouriteExistOrNot(service.ProductId, uId)
	if exist {
		code = e.ErrorFavouriteExist
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	userDao := dao.NewUserDao(ctx)
	user, err := userDao.GetUserById(uId)
	if err != nil {
		code = e.Error
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	bossDao := dao.NewUserDao(ctx)
	boss, err := bossDao.GetUserById(service.BossId)
	if err != nil {
		code = e.Error
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}

	productDao := dao.NewProductDao(ctx)
	product, err := productDao.GetProductById(service.ProductId)
	if err != nil {
		code = e.Error
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	favourite := &model.Favourite{
		User:      *user,
		UserId:    uId,
		Product:   *product,
		ProductId: service.ProductId,
		Boss:      *boss,
		BossId:    service.BossId,
	}
	err = favouriteDao.CreateFavourite(favourite)
	if err != nil {
		code = e.Error
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	return serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
	}
}

func (service *FavouriteService) Delete(ctx context.Context, uId uint, fid string) serializer.Response {
	favouriteDao := dao.NewFavouriteDao(ctx)
	code := e.Success
	favouriteId, _ := strconv.Atoi(fid)
	err := favouriteDao.DeleteFavourite(uId, uint(favouriteId))
	if err != nil {
		utils.LogrusObj.Infoln("err", err)
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
			Error:  err.Error(),
		}
	}
	return serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
	}
}
